import React, { useEffect, useState } from 'react';
import { Layout, Menu, Avatar, Dropdown } from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  LogoutOutlined,
  MenuOutlined,
  HomeOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation, Routes, Route, Navigate, Link } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { loginStore } from '../../store/public/loginStore';
import { menuStore } from '../../store/public/menuStore';
import * as Icons from '@ant-design/icons';
import styles from './EngineLayout.module.css';
import { routesEngine } from '../../routes/lib';
import { systemName } from '../../globals/system.tsx';

import bannerImg from '@/assets/banner.png';

const { Header, Sider, Content } = Layout;

/**
 * 后台布局
 */
const EngineLayout: React.FC = observer(() => {
  const navigate = useNavigate();
  const location = useLocation();
  const [collapsed, setCollapsed] = useState(false);

  useEffect(() => {
    // 从 loginStore 中读取登录状态
    if (!loginStore.isAuthenticated) {
      navigate('/login');
    }
  }, [navigate]);

  // 登出功能
  const handleLogout = () => {
    loginStore.logout();
    navigate('/login');
  };

  // 根据当前路径判断应该选中的菜单项
  const getSelectedKeys = () => {
    const path = location.pathname;
    const selected = menuStore.items_engine.find(item =>
      path.includes(item.path.replace('/engine', ''))
    );
    return selected ? [selected.key] : ['1'];
  };

  const renderHeader = () => {

    let username = '';
    let avatarUrl = '';
    if (window.HubUser) {
      username = window.HubUser?.username;
      if(window.HubUser?.avatar){
        avatarUrl = `/api/starhub/document/download/${window.HubUser?.avatar}`;
      }
    }
    return (
      <Header className={styles['statHub-engine-header']}>
        <div
          className={styles['statHub-engine-collapse-btn']}
          onClick={() => setCollapsed(!collapsed)}
        >
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </div>
        <div className={styles['statHub-engine-user-container']}>
          <Dropdown menu={{
            items: [
              {
                key: '1',
                icon: <HomeOutlined />,
                label: '返回前台',
                onClick: () => navigate('/app/ai-assistant')
              },
              {
                key: '2',
                icon: <LogoutOutlined />,
                label: '退出登录',
                onClick: handleLogout
              }
            ]
          }}>
            <div className={styles['statHub-engine-user-info']}>
              <Avatar icon={<UserOutlined />} src={avatarUrl}  />
              <span className={styles['statHub-engine-user-name']}>{username}</span>
            </div>
          </Dropdown>
        </div>
      </Header>
    )
  }
  return (
    <Layout className={styles['statHub-engine-container']}>
      <Sider
        width={220}
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        className={styles['statHub-engine-sider']}
      >
        <div className={`${styles['statHub-engine-logo']} ${collapsed ? styles['statHub-engine-logo-collapsed'] : ''}`}>
          {!collapsed && (<><img className="starHub-system-logo" src={bannerImg}/>{systemName}</>)}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={getSelectedKeys()}
          className={styles['statHub-engine-menu']}
        >
          {menuStore.items_engine.map(item => {
            if (item.children) {
              return (
                <Menu.SubMenu
                  key={item.key}
                  icon={item.icon && (Icons as any)[item.icon] ? React.createElement((Icons as any)[item.icon]) : null}
                  title={item.label}
                >
                  {item.children.map(child => (
                    <Menu.Item key={child.key}>
                      <Link to={child.path}>{child.label}</Link>
                    </Menu.Item>
                  ))}
                </Menu.SubMenu>
              );
            }
            return (
              <Menu.Item
                key={item.key}
                icon={item.icon && (Icons as any)[item.icon] ? React.createElement((Icons as any)[item.icon]) : null}
              >
                <Link to={item.path}>{item.label}</Link>
              </Menu.Item>
            );
          })}
        </Menu>
      </Sider>
      <Layout className={`${styles['statHub-engine-main']} ${collapsed ? styles['statHub-engine-main-collapsed'] : ''}`}>
        {renderHeader()}
        <Content className={styles['statHub-engine-content']}>
          <div className={styles['statHub-engine-content-inner']}>
            <Routes>
              <Route index element={<Navigate to="/engine/dashboard" replace />} />
              {routesEngine.map(route => (
                <Route path={route.path} element={route.element} />
              ))}
            </Routes>
          </div>
        </Content>
      </Layout>
    </Layout>
  );
});

export default EngineLayout; 